<template>
	<view class="videoBox relative">
		<image class=" wid1p radius20 z-index-5" :src="CoverImg" mode="scaleToFill">
			<view class="center-center z-index-10 icoBox"><text class="cuIcon-video fo-80 fo-white"></text></view>
			<view class="right-bottom">
				<text>{{ VideoTimes }}</text>
			</view>
		</image>
	</view>
</template>

<script>
export default {
	props: {
		VideoInfo: {
			type: String,
			default: ''
		}
	},
	name: '',
	data() {
		return {
			data_info: '', // 组件传递的数据
			CoverImg: '', // 封面图片
			VideoTimes: '' // 视频时长
		};
	},
	watch:{
		async VideoInfo(){
			await this.init()
		}
	},
	async mounted() {
		await this.init()
	},
	methods: {
		// init
		async init(){
			this.data_info = this.VideoInfo;
			let { width, height } = await this.getVideoHeiWid(this.data_info);
			let res = await this.getVideoBase64(this.data_info);
			this.CoverImg = res;
		},
		// 获取视频的宽度和高度
		getVideoHeiWid(url) {
			return new Promise((resolve, reject) => {
				var video = document.createElement('video');
				video.autoplay = true;
				video.oncanplay = function() {
					resolve({ width: this.offsetWidth, height: this.offsetHeight });
					// this.src = 'about:blank';
					document.body.removeChild(video);
				};

				document.body.appendChild(video);
				video.src = url;
			});
		},
		// 获取视频封面
		async getVideoBase64(url) {
			let that = this;
			let { width, height } = await this.getVideoHeiWid(this.data_info);
			return new Promise(function(resolve, reject) {
				let dataURL = '';
				let video = document.createElement('video');
				video.remove();

				video.setAttribute('crossOrigin', 'anonymous'); //处理跨域
				video.setAttribute('src', url);
				video.currentTime = 1; // 指定播放位置
				video.addEventListener('loadeddata', function(e) {
					
					// 视频时长转化
					let hour = Math.floor(video.duration / (60 * 60));
					let min = Math.floor(video.duration / 60);
					let seconds = Math.floor(video.duration % 60);
					that.VideoTimes = hour + ':' + min + ':' + seconds;

					let canvas = document.createElement('canvas');
					canvas.width = width;
					canvas.height = height;
					canvas.getContext('2d').drawImage(video, 0, 0, width, height); //绘制canvas
					dataURL = canvas.toDataURL('image/jpeg'); //转换为base64

					resolve(dataURL);
				});
			});
		}
	}
};
</script>

<style lang="less" scoped>
.bg-black-04 {
}
.z-index-5 {
	z-index: 5;
}
.z-index-10 {
	z-index: 10;
}
.right-bottom {
	position: absolute;
	right: 20rpx;
	bottom: 20rpx;
	color: #fff;
	border-radius: 20rpx;
	padding: 10rpx 20rpx;
	background-color: rgba(0, 0, 0, 0.4);
	z-index: 10;
}
.icoBox {
	background-color: rgba(0, 0, 0, 0.4);
	border-radius: 20rpx;
	padding: 10rpx 20rpx;
}
</style>
